package data;

import java.sql.*;
import java.util.*;

public abstract class DataFactory
{
    private String m_TableName;
    private String m_KeySequence;
    private Database m_Database;
    
    protected DataFactory( String tableName, String keySeq, Database db )
    {
	m_TableName = tableName;
	m_KeySequence = keySeq;
	m_Database = db;
    }
	
    public DataElement _findOne( String conditions )
    {
		return (DataElement) find( conditions ).getFirst();
    }

    public LinkedList find( String conditions )
    {
		String sql = "select * from " + m_TableName + " where " + conditions;
		ResultSet rs = m_Database.execQuery( sql );
		return listFromResultSet( rs );
    }

    public LinkedList findAll()
    {
		String sql = "select * from " + m_TableName;
		ResultSet rs = m_Database.execQuery( sql );
		return listFromResultSet( rs );
    }

    public DataElement _create()
    {
		return instantiate();
    }

    public DataElement _lookup( int id )
    {
	String sql = "select * from " + m_TableName + " where id=" + id;
	ResultSet rs = m_Database.execQuery( sql );
	
	try {
	    if( !rs.next() ) {
		System.err.println( "Data lookup error: key not present" );
		System.exit(1);
	    } else {
		return build( rs );
	    }
	} catch( SQLException sqle ) {
	    System.err.println( "SQL Error: " + sqle.getMessage() );
	    sqle.printStackTrace();
	    System.exit(1);
	}
	return null;
    }

    public void destroy( int id )
    {
		String sql = "delete from " + m_TableName + " where id=" + id;
		m_Database.execUpdate( sql );
    }
	
	public String getTableName()
	{
		return m_TableName;
	}
	
    public String getKeySequence()
    {
	return m_KeySequence;
    }
    
	public Database getDatabase()
	{
		return m_Database;
	}

    public DataElement build( ResultSet rs )
	{
		DataElement o = instantiate();
		o.loadFrom( rs );
		return o;
	}
	
	protected LinkedList listFromResultSet( ResultSet rs )
	{
		LinkedList l = new LinkedList();
		
		try {
		        while( rs.next() ) {
			    l.add( build( rs ) );
				
			}
		} catch( SQLException sqle ) {
			System.err.println( "SQL Error: " + sqle.getMessage() );
			sqle.printStackTrace();
			System.exit(1);
		}
		
		return l;
	}
	
	protected abstract DataElement instantiate();
	
}
